package com.ruoyi.order.service.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.OConvertUtils;
import com.ruoyi.common.utils.OrderIdGenerator;
import com.ruoyi.order.domain.*;
import com.ruoyi.order.mapper.*;
import com.ruoyi.order.vo.OrderDetailVo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.order.service.ITbProductOrderService;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * 订单Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-19
 */
@Service
public class TbProductOrderServiceImpl implements ITbProductOrderService 
{
    @Autowired
    private TbProductOrderMapper tbProductOrderMapper;
    @Autowired
    private TbTemplateMapper tbTemplateMapper;

    /**
     * 查询订单
     * 
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public TbProductOrder selectTbProductOrderById(Long id)
    {
        return tbProductOrderMapper.selectTbProductOrderById(id);
    }

    /**
     * 查询订单列表
     * 
     * @param tbProductOrder 订单
     * @return 订单
     */
    @Override
    public List<TbProductOrder> selectTbProductOrderList(TbProductOrder tbProductOrder)
    {
        return tbProductOrderMapper.selectTbProductOrderList(tbProductOrder);
    }

    /**
     * 新增订单
     * 
     * @param tbProductOrder 订单
     * @return 结果
     */
    @Override
    public int insertTbProductOrder(TbProductOrder tbProductOrder)
    {
        tbProductOrder.setCreateTime(DateUtils.getNowDate());
        return tbProductOrderMapper.insertTbProductOrder(tbProductOrder);
    }

    /**
     * 修改订单
     * 
     * @param tbProductOrder 订单
     * @return 结果
     */
    @Override
    public int updateTbProductOrder(TbProductOrder tbProductOrder)
    {
        return tbProductOrderMapper.updateTbProductOrder(tbProductOrder);
    }

    /**
     * 批量删除订单
     * 
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteTbProductOrderByIds(Long[] ids)
    {
        return tbProductOrderMapper.deleteTbProductOrderByIds(ids);
    }

    /**
     * 删除订单信息
     * 
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public int deleteTbProductOrderById(Long id)
    {
        return tbProductOrderMapper.deleteTbProductOrderById(id);
    }

    @Resource
    private TbProductWholeasalePriceMapper tbProductWholeasalePriceMapper;
    @Resource
    private TbProductMapper tbProductMapper;
    @Resource
    private TbProductWholesaleMapper tbProductWholesaleMapper;
    @Resource
    private TbProductOrderDetailMapper tbProductOrderDetailMapper;
    @Resource
    private TbProductSpecificationMapper tbProductSpecificationMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int createOrder(OrderInfo orderInfo) {
        if (orderInfo == null) {
            throw new IllegalArgumentException("订单信息不能为空");
        }
        List<OrderDetailInfo> list = orderInfo.getDetailInfoList();
        // 1. 批量获取所有商品规格信息
        List<Long> specificationIds = list.stream()
                .map(OrderDetailInfo::getProductSpecificationId)
                .distinct()
                .collect(Collectors.toList());
        Map<Long, TbProductSpecification> specificationMap = tbProductSpecificationMapper
                .selectTbProductSpecificationByIds(specificationIds)
                .stream()
                .collect(Collectors.toMap(TbProductSpecification::getId, Function.identity()));

        // 2. 批量获取所有商品信息
        List<Long> productIds = specificationMap.values().stream()
                .map(TbProductSpecification::getProductId)
                .distinct()
                .collect(Collectors.toList());

        Map<Long, TbProduct> productMap = tbProductMapper
                .selectTbProductByIds(productIds)
                .stream()
                .collect(Collectors.toMap(TbProduct::getId, Function.identity()));

        // 3. 批量获取所有商品类型的批发规格
        List<Long> productTypeIds = productMap.values().stream()
                .map(TbProduct::getProductTypeId)
                .distinct()
                .collect(Collectors.toList());

        List<TbProductWholesale> allWholesales = tbProductWholesaleMapper
                .selectTbproductWholesaleListByTypeIds(productTypeIds);

        // 按商品类型分组
        Map<Long, List<TbProductWholesale>> wholesalesByType = allWholesales.stream()
                .collect(Collectors.groupingBy(TbProductWholesale::getProductTypeId));

        // 4. 批量获取所有批发价格
        List<Long> wholesaleIds = allWholesales.stream()
                .map(TbProductWholesale::getId)
                .collect(Collectors.toList());

        Map<Long, TbProductWholeasalePrice> priceMap = tbProductWholeasalePriceMapper
                .selectTbProductWholeasalePriceByWholesaleIds(wholesaleIds)
                .stream()
                .collect(Collectors.toMap(TbProductWholeasalePrice::getProductWholeasaleId, Function.identity()));

        // 5. 构建订单和订单详情
        TbProductOrder tbProductOrder = buildOrder(orderInfo);
        List<TbProductOrderDetail> orderDetails = new ArrayList<>();

        for (OrderDetailInfo detailInfo : list) {
            Long specificationId = detailInfo.getProductSpecificationId();
            Long nums = detailInfo.getNums();

            TbProductSpecification specification = specificationMap.get(specificationId);
            if (specification == null) {
                throw new RuntimeException("商品规格不存在: " + specificationId);
            }

            TbProduct product = productMap.get(specification.getProductId());
            if (product == null) {
                throw new RuntimeException("商品不存在: " + specification.getProductId());
            }

            TbProductOrderDetail detail = new TbProductOrderDetail();
            detail.setProductId(product.getId());
            detail.setSpecificationId(specificationId);

            // 找到合适的批发价格
            List<TbProductWholesale> typeWholesales = wholesalesByType.get(product.getProductTypeId());
            if (typeWholesales == null || typeWholesales.isEmpty()) {
                detail.setUnitPrice(specification.getProductPrice());
            }else{
                typeWholesales.sort(Comparator.comparing(TbProductWholesale::getNum,
                        Comparator.nullsLast(Long::compareTo)).reversed());

                Long priceId = typeWholesales.stream()
                        .filter(w -> nums >= w.getNum())
                        .map(TbProductWholesale::getId)
                        .findFirst().orElse(null);
                TbProductWholeasalePrice price = priceMap.get(priceId);
                if (price == null) {
                    detail.setUnitPrice(specification.getProductPrice());
                }else{
                    detail.setPriceId(price.getId());
                    detail.setUnitPrice(price.getPrice());
                }
            }
            detail.setNums(nums);
            detail.setSumPrice(detailInfo.getSumPrice());
            detail.setOrderId(tbProductOrder.getOrderId());
            detail.setCreateTime(DateUtils.getNowDate());
            orderDetails.add(detail);
        }

        // 计算总金额并保存
        BigDecimal totalAmount = orderDetails.stream()
                .map(TbProductOrderDetail::getSumPrice)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        tbProductOrder.setSumPrice(totalAmount);
        tbProductOrder.setCreateTime(DateUtils.getNowDate());
        tbProductOrder.setCreateBy(orderInfo.getCreateBy());
        tbProductOrder.setCreateUserId(orderInfo.getCreateUserId());
        int result = tbProductOrderMapper.insertTbProductOrder(tbProductOrder);
        orderDetails.forEach(detail ->{
            detail.setOrderId(tbProductOrder.getOrderId());
            detail.setCreateTime(new Date());
            detail.setCreateBy(orderInfo.getCreateBy());

        });
        tbProductOrderDetailMapper.insertBatch(orderDetails);
        return result;
    }

    @Override
    public void editOrder(OrderInfo orderInfo) {
        TbProductOrder order = tbProductOrderMapper.selectTbProductOrderById(orderInfo.getId());
        order.setBuyerName(orderInfo.getBuyerName());
        order.setBuyerPhone(orderInfo.getBuyerPhone());
        order.setBuyerAddress(orderInfo.getBuyerAddress());
        order.setBuyerContry(orderInfo.getBuyerContry());
        order.setTradeId(orderInfo.getTradeId());


        List<OrderDetailInfo> detailInfoList = orderInfo.getDetailInfoList();
        // 1. 批量获取所有商品规格信息
        List<Long> specificationIds = detailInfoList.stream()
                .map(OrderDetailInfo::getProductSpecificationId)
                .distinct()
                .collect(Collectors.toList());
        Map<Long, TbProductSpecification> specificationMap = tbProductSpecificationMapper
                .selectTbProductSpecificationByIds(specificationIds)
                .stream()
                .collect(Collectors.toMap(TbProductSpecification::getId, Function.identity()));

        // 2. 批量获取所有商品信息
        List<Long> productIds = specificationMap.values().stream()
                .map(TbProductSpecification::getProductId)
                .distinct()
                .collect(Collectors.toList());

        Map<Long, TbProduct> productMap = tbProductMapper
                .selectTbProductByIds(productIds)
                .stream()
                .collect(Collectors.toMap(TbProduct::getId, Function.identity()));

        // 3. 批量获取所有商品类型的批发规格
        List<Long> productTypeIds = productMap.values().stream()
                .map(TbProduct::getProductTypeId)
                .distinct()
                .collect(Collectors.toList());

        List<TbProductWholesale> allWholesales = tbProductWholesaleMapper
                .selectTbproductWholesaleListByTypeIds(productTypeIds);

        // 按商品类型分组
        Map<Long, List<TbProductWholesale>> wholesalesByType = allWholesales.stream()
                .collect(Collectors.groupingBy(TbProductWholesale::getProductTypeId));

        // 4. 批量获取所有批发价格
        List<Long> wholesaleIds = allWholesales.stream()
                .map(TbProductWholesale::getId)
                .collect(Collectors.toList());

        List<TbProductWholeasalePrice> tbProductWholeasalePrices = tbProductWholeasalePriceMapper
                .selectTbProductWholeasalePriceByWholesaleIds(wholesaleIds);

        Map<Long, TbProductWholeasalePrice> priceMap = tbProductWholeasalePrices.stream().collect(Collectors.toMap(TbProductWholeasalePrice::getProductWholeasaleId, Function.identity()));


        List<TbProductOrderDetail> addList = new ArrayList<>();
        List<TbProductOrderDetail> updateList = new ArrayList<>();

        for (OrderDetailInfo detailInfo : detailInfoList) {
            Long specificationId = detailInfo.getProductSpecificationId();
            Long nums = detailInfo.getNums();

            TbProductSpecification specification = specificationMap.get(specificationId);
            if (specification == null) {
                throw new RuntimeException("商品规格不存在: " + specificationId);
            }

            TbProduct product = productMap.get(specification.getProductId());
            if (product == null) {
                throw new RuntimeException("商品不存在: " + specification.getProductId());
            }

            TbProductOrderDetail detail = new TbProductOrderDetail();
            detail.setProductId(product.getId());
            detail.setSpecificationId(specificationId);

            // 找到合适的批发价格
            List<TbProductWholesale> typeWholesales = wholesalesByType.get(product.getProductTypeId());
            if (typeWholesales == null || typeWholesales.isEmpty()) {
                detail.setUnitPrice(specification.getProductPrice());
            }else{
                typeWholesales.sort(Comparator.comparing(TbProductWholesale::getNum,
                        Comparator.nullsLast(Long::compareTo)).reversed());

                Long priceId = typeWholesales.stream()
                        .filter(w -> nums >= w.getNum())
                        .map(TbProductWholesale::getId)
                        .findFirst().orElse(null);
                TbProductWholeasalePrice price = priceMap.get(priceId);
                if (price == null) {
                    detail.setUnitPrice(specification.getProductPrice());
                }else{
                    detail.setPriceId(price.getId());
                    detail.setUnitPrice(price.getPrice());
                }

            }
            detail.setNums(nums);
            detail.setSumPrice(detailInfo.getSumPrice());
            detail.setOrderId(order.getOrderId());
            detail.setCreateTime(DateUtils.getNowDate());

            if (OConvertUtils.isEmpty(detailInfo.getId())){
                addList.add(detail);
            }else{
                detail.setId(detail.getId());
                tbProductOrderDetailMapper.updateTbProductOrderDetail(detail);
                updateList.add(detail);
            }

        }

        // 计算总金额并保存
        BigDecimal totalAmount = addList.stream()
                .map(TbProductOrderDetail::getSumPrice)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal totalAmount2 = updateList.stream()
                .map(TbProductOrderDetail::getSumPrice)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        order.setSumPrice(totalAmount.add(totalAmount2));
        tbProductOrderMapper.updateTbProductOrder(order);
        if (OConvertUtils.listIsNotEmpty(addList)){
            tbProductOrderDetailMapper.insertBatch(addList);
        }
    }

    @Override
    public String buildWorkContent(TbProductOrder tbProductOrder, String templateId) {
        // 创建内容
        String returnStr = "";
        List<TbProductOrder> tbProductOrders = this.tbProductOrderMapper.selectTbProductOrderList(tbProductOrder);
        List<String> orderIds = tbProductOrders.stream().map(TbProductOrder::getOrderId).collect(Collectors.toList());
        List<OrderDetailVo> orderDetailVos = tbProductOrderDetailMapper.listByOrderIds(orderIds);
        Map<String, List<OrderDetailVo>> detailVoMap = orderDetailVos.stream()
                .collect(Collectors.groupingBy(OrderDetailVo::getOrderId));
        TbTemplate tbTemplate = tbTemplateMapper.selectTbTemplateById(Long.valueOf(templateId));
        TbTemplate childrenTemp = new TbTemplate();
        if (OConvertUtils.isNotEmpty(tbTemplate) && OConvertUtils.isNotEmpty(tbTemplate.getTemplateChildrenId())){
             childrenTemp = tbTemplateMapper.selectTbTemplateById(tbTemplate.getTemplateChildrenId());
        }

        int sno = 1;
        for (TbProductOrder order : tbProductOrders) {
            List<OrderDetailVo> detailVos = detailVoMap.get(order.getOrderId());
            String s = replaceContentTxt(tbTemplate, childrenTemp, order, detailVos, sno);
            returnStr += s + "\n";
            sno++;
        }
        return returnStr;
    }

    @Override
    public List<ExportOrderVo> selectExportVo(TbProductOrder tbProductOrder) {
        return tbProductOrderMapper.selectExportVo(tbProductOrder);
    }

    private String replaceContentTxt(TbTemplate tbTemplate,
                                     TbTemplate chileDrenTemplate,
                                     TbProductOrder order,
                                     List<OrderDetailVo> detailVos,
                                     int sno){
        String orderText = tbTemplate.getContext();
        orderText = orderText.replace("{orderId}", order.getOrderId()); // 订单编号
        orderText = orderText.replace("{buyerName}", order.getBuyerName()); // 客户名称
        orderText = orderText.replace("{buyerAddress}", order.getBuyerAddress()); // 客户地址
        orderText = orderText.replace("{buyerPhone}", order.getBuyerPhone()); // 客户电话
        orderText = orderText.replace("{buyerContry}", order.getBuyerContry()); // 客户国家
        orderText = orderText.replace("{tradeId}", order.getTradeId()); // 追踪单号
        orderText = orderText.replace("{sumPrice}", String.valueOf(order.getSumPrice())); // 最终金额
        orderText = orderText.replace("{date}",DateUtils.parseDateToStr(DateUtils.MM_DD,order.getCreateTime())); // 最终金额
        orderText = orderText.replace("{no}", String.valueOf(sno) ); // 最终金额
        if (orderText.contains("{item}")) {
            String itemText = "";
            for (OrderDetailVo detail : detailVos) {
                String detailText = chileDrenTemplate.getContext();

                // 替换所有可能的字段名，兼容不同的数据结构
                detailText = detailText.replace(
                        "{productName}",
                        detail.getProductName()
                ); // 商品名称
                detailText = detailText.replace(
                        "{productOtherName}",
                        detail.getProductOtherName()
                ); // 商品别名
                detailText = detailText.replace(
                        "{productSpecification}",
                        detail.getProductSpecification()
                ); // 规格
                detailText = detailText.replace(
                        "{productPrice}",
                        detail.getProductPrice()
                ); // 商品价格
                detailText = detailText.replace(
                        "{unitPrice}",
                        OConvertUtils.isEmpty(detail.getPrice())?"0":detail.getPrice()
                ); // 单价
                detailText = detailText.replace(
                        "{nums}",
                        detail.getNums()
                ); // 购买数量
                detailText = detailText.replace(
                        "{sumPrice}",
                        detail.getSumPrice()
                ); // 报价

                detailText = detailText.replace(
                        "{productNo}",
                        detail.getProductNo()
                ); // 商品编号

                detailText = detailText.replace(
                        "{productTYpeName}",
                        detail.getProductTYpeName()
                ); // 报价
                itemText += detailText + "\n";
            }
            orderText = orderText.replace("{item}", itemText);
        }
        return orderText;
    }


    private TbProductOrder buildOrder(OrderInfo orderInfo) {
        TbProductOrder order = new TbProductOrder();
        order.setOrderId(OrderIdGenerator.generateOrderId());
        order.setBuyerName(orderInfo.getBuyerName());
        order.setBuyerAddress(orderInfo.getBuyerAddress());
        order.setBuyerPhone(orderInfo.getBuyerPhone());
        order.setBuyerContry(orderInfo.getBuyerContry());
        order.setTradeId(orderInfo.getTradeId());
        order.setStatus(0L);
        order.setUserNickName(orderInfo.getUserNickName());
        order.setSocialApp(orderInfo.getSocialApp());
        order.setPaymentNo(orderInfo.getPaymentNo());
        order.setConfirmTime(orderInfo.getConfirmTime());
        return order;
    }
}
